//
//  FQDFeedCellItemProvider.m
//  FakeQDaily
//
//  Created by mewxiv on 8/29/16.
//  Copyright © 2016 Xensius. All rights reserved.
//

#import "FQDFeedCellItemProvider.h"
#import "FQDFeedCache.h"
#import "FQDNetworkTool.h"
#import "MBProgressHUD+FQDExtension.h"

static NSString *const kFeedLatestCursorKey = @"0";
static NSString *const kDefaultFeedId = @"0";

@interface FQDFeedCellItemProvider ()
@property (nonatomic, strong, readwrite) NSArray *cellItems;
// 获取更多之前的feeds的key
@property (nonatomic, strong) NSString *lastKey;
// 是否有更多的数据
@property (nonatomic, assign) BOOL hasMore;
// 是否获得服务器响应
@property (nonatomic, assign) BOOL isRequested;
// 正在加载的请求个数
@property (nonatomic, assign) NSInteger loadingRequestCount;
@end

@implementation FQDFeedCellItemProvider

- (instancetype)init
{
    self = [super init];
    if (self) {
        _loadingRequestCount = 0;
    }
    return self;
}

- (void)loadNewCellItems:(void (^)(BOOL isSuccess))completion
{
    NSString *const cursorKey = kFeedLatestCursorKey;
    [self loadCellItems:cursorKey completion:completion];
}

- (void)loadMoreCellItems:(void (^)(BOOL isSuccess))completion
{
    NSString *const cursorKey = self.lastKey ? : kFeedLatestCursorKey;
    [self loadCellItems:cursorKey completion:completion];
}

- (void)loadCellItems:(NSString *)cursorKey completion:(void (^)(BOOL isSuccess))completion
{
    NSParameterAssert(cursorKey != nil);
    if ([[FQDNetworkTool sharedInstance] isNetworkReachable]) {
        self.loadingRequestCount += 1;
        WeakSelf;
        [self getCellItems:cursorKey completion:^(id responseObject, NSError *error) {
            NSNumber *status = [responseObject valueForKeyPath:@"meta.status"];
            weakSelf.isRequested = (status != nil);
            if ([status integerValue] == 200) {
                id response = responseObject[@"response"];
                [weakSelf handleResponse:response cursorKey:cursorKey];
                [weakSelf cacheFeeds:response cursorKey:cursorKey];
                completion(YES);
            } else {
                NSString *errorMsg = [responseObject valueForKeyPath:@"meta.msg"];
                NSString *errorDesc = errorMsg ? : [error localizedDescription];
                FQDLog(@"Error fetch Data:%@ from QDaily", errorDesc);
                [weakSelf loadCellItemsFromCache:cursorKey completion:completion];
            }
            weakSelf.loadingRequestCount -= 1;
        }];
    } else {
        [MBProgressHUD showNotReachableMessage];
        [self loadCellItemsFromCache:cursorKey completion:completion];
    }
}

- (void)handleResponse:(id)responseObject cursorKey:(NSString *)cursorKey
{
    NSDictionary *response = responseObject;
    
    self.hasMore = [response[@"has_more"] boolValue];
    self.lastKey = response[@"last_key"];
    
    BOOL isLatest = (cursorKey == kFeedLatestCursorKey);
    if (isLatest) {
        self.cellItems = [NSArray array];
    }
    [self parseResponse:response isLatest:isLatest];
    
    
    NSMutableArray *originalCellItems = [self.cellItems mutableCopy];
    [self populateNewCellItemsTo:originalCellItems];
    self.cellItems = [originalCellItems copy];
}

- (void)clearData
{
    self.cellItems = [NSArray array];
}

- (void)modifyCellItemsWithBlock:(void (^)(NSMutableArray *originalCellItems))modifyBlock
{
    if (modifyBlock) {
        NSMutableArray *originalCellItems = [self.cellItems mutableCopy];
        modifyBlock(originalCellItems);
        self.cellItems = [originalCellItems copy];
    }
}

#pragma mark - Override methods
- (void)getCellItems:(NSString *)cursorKey completion:(QDailyAPICompleteBlock)completion
{
    NSDictionary *userInfo = @{NSLocalizedDescriptionKey : @"subclass must override getCellItems:completion!"};
    NSError *error = [NSError errorWithDomain:@"org.xensius.fakeqdaily" code:-1 userInfo:userInfo];
    completion(nil, error);
}

- (void)parseResponse:(id)response isLatest:(BOOL)isLatest
{
    
}

- (void)populateNewCellItemsTo:(NSMutableArray *)originalCellItems
{
    
}

- (NSString *)cacheId
{
    return nil;
}

- (NSString *)feedId
{
    return _feedId ? : kDefaultFeedId;
}

#pragma mark - Cache
- (void)cacheFeeds:(id)responseObject cursorKey:(NSString *)cursorKey
{
    NSString *cacheId = [self cacheId];
    if (cacheId) {
        FQDFeedCacheItem *feedCache = [FQDFeedCacheManager cacheForIdentifier:cacheId];
        [feedCache cacheFeeds:responseObject feedId:[self feedId] cursorKey:cursorKey];
    }
}

- (void)loadCellItemsFromCache:(NSString *)cursorKey completion:(void (^)(BOOL isSuccess))completion
{
    NSString *cacheId = [self cacheId];
    if (cacheId) {
        FQDFeedCacheItem *feedCache = [FQDFeedCacheManager cacheForIdentifier:cacheId];
        WeakSelf;
        [feedCache loadFeedsFromCache:[self feedId] cursorKey:cursorKey completion:^(id response) {
            if (response) {
                [weakSelf handleResponse:response cursorKey:cursorKey];
            }
            BOOL isSuccess = (response != nil);
            completion(isSuccess);
        }];
    } else {
        completion(NO);
    }

}

#pragma mark - Getters and Setters
- (BOOL)hasMoreCellItems
{
    // 未请求数据默认为有更多数据
    return (self.hasMore || !self.isRequested);
}

- (BOOL)isLoadingCellItems
{
    return (self.loadingRequestCount > 0);
}

// 信息流集合懒加载
- (NSArray *)cellItems
{
    if (!_cellItems) {
        _cellItems = [NSArray array];
    }
    return _cellItems;
}

@end